package com.chukun.flink.dataset.operator;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple3;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chukun
 * @version 1.0.0
 * @description reduce 操作符的基本操作
 * @createTime 2022年05月28日 20:35:00
 */
public class ReduceOperator {

    public static void main(String[] args) throws Exception {

        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        List<Tuple3<String, Integer, String>> list = new ArrayList<>();
        list.add(new Tuple3<>("185XXX", 899, "周一"));
        list.add(new Tuple3<>("155XXX", 1199, "周二"));
        list.add(new Tuple3<>("155XXX", 899, "周一"));

        DataSet<Tuple3<String, Integer, String>> sourceDataSet = env.fromCollection(list);

        DataSet<Tuple3<String, Integer, String>> reduce = sourceDataSet.groupBy((key) -> key.f0)
                .reduce(new ReduceFunction<Tuple3<String, Integer, String>>() {
                    @Override
                    public Tuple3<String, Integer, String> reduce(Tuple3<String, Integer, String> tuple01, Tuple3<String, Integer, String> tuple02) throws Exception {
                        return Tuple3.of(tuple01.f0, tuple01.f1 + tuple01.f1, tuple01.f2);
                    }
                });

        reduce.print("ReduceFunction");

        env.execute("ReduceOperator");
    }
}
